import { Cascader, Switch, Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import PubNav from '../../components/publicComponents/pubNav'
import style from './addAddress.module.css'
import options from '../../utils/area'
import http from '../../api'
import Loading from '../../components/publicComponents/Loading'

export default function AddAddress() {
  const location = useLocation()
  const [visible, setVisible] = useState(false)
  const navigate = useNavigate()
  const [checked, setChecked] = useState(false)
  const [tag, setTag] = useState<0 | 1 | 2>(0)
  const [name, setName] = useState('')
  const [mobile, setMobile] = useState('')
  const [province, setProvince] = useState('省、')
  const [city, setCity] = useState('城市、')
  const [county, setCounty] = useState('区、街道等')
  const [address, setAddress] = useState('')
  let [userId, setUserId] = useState('')
  let [id, setId] = useState('')

  useEffect(() => {
    if (location.state) {
      setId(location.state.id)
      setChecked(location.state.item.status === 0 ? false : true)
      setTag(() => {
        if (location.state.item.type === 0) {
          return 0
        } else if (location.state.item.type === 1) {
          return 1
        } else {
          return 2
        }
      })
      setName(location.state.item.name)
      setMobile(location.state.item.tel)
      setProvince(location.state.item.province)
      setCity(location.state.item.city)
      setCounty(location.state.item.area)
      setAddress(location.state.item.specificAddress)
    }
    const id = localStorage.getItem('userId')
    if (id) {
      userId = id
      setUserId(id)
    } else {
      navigate('/login')
    }
  }, [])

  async function submit() {
    if (name === '')
      return Toast.show({
        content: '请填写收货人信息'
      })
    if (!/^1[3-9]\d{9}$/.test(mobile))
      return Toast.show({
        content: '手机号格式错误'
      })
    if (province === '省、' || city === '城市、' || county === '区、街道等')
      return Toast.show({
        content: '请填写收货地址'
      })
    if (!province || !city || !county)
      return Toast.show({
        content: '收货地址错误'
      })
    if (!address)
      return Toast.show({
        content: '请填写详细地址'
      })

    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })

    const data = {
      id: id ? id : '',
      name: name,
      tel: mobile,
      userId: userId,
      province: province,
      city: city,
      area: county,
      specificAddress: address,
      status: checked ? 1 : 0,
      type: tag
    }
    const result = await http('post', '/mty/shippingAddress/saveOrEdit', data)
    Toast.clear()
    if (result && result.code === 200) {
      navigate(-1)
    }
  }

  return (
    <div style={{ paddingTop: '46px' }}>
      <PubNav title="新增地址" />
      <div className={style['address-info']}>
        <div className={style['address-item']}>
          <div className={style['address-label']}>收货人:</div>
          <div className={style['address-ipt']}>
            <input
              type="text"
              placeholder="请填写收货人信息"
              value={name}
              onChange={(e) => {
                setName(e.target.value)
              }}
            />
          </div>
        </div>
        {/* 联系电话 */}
        <div className={style['address-item']}>
          <div className={style['address-label']}>联系手机:</div>
          <div className={style['address-ipt']}>
            <input
              type="text"
              placeholder="请填写收货人手机号码"
              value={mobile}
              onChange={(e) => {
                setMobile(e.target.value)
              }}
            />
          </div>
        </div>
        {/* 选择地址 */}
        <div
          className={style['address-item']}
          onClick={() => {
            setVisible(true)
          }}
        >
          <div className={style['address-label']}>选择地址:</div>
          <div className={style['address-ipt']}>{province + ' ' + city + ' ' + county}</div>
        </div>
        {/* 详细地址 */}
        <div className={style['address-item']}>
          <div className={style['address-label']}>详细地址:</div>
          <div className={style['address-ipt']}>
            <input
              type="text"
              placeholder="街道、楼牌号等"
              value={address}
              onChange={(e) => {
                setAddress(e.target.value)
              }}
            />
          </div>
        </div>
      </div>

      {/* 标签 */}
      <div className={style['tag']}>
        <div className={style['tag-item']}>
          <div className={style['title']}>标签:</div>
          <div className={style['tags']}>
            <div
              className={`${style['tags-item']} ${tag === 0 && style['active']}`}
              onClick={() => {
                setTag(0)
              }}
            >
              家
            </div>
            <div
              className={`${style['tags-item']} ${tag === 1 && style['active']}`}
              onClick={() => {
                setTag(1)
              }}
            >
              公司
            </div>
            <div
              className={`${style['tags-item']} ${tag === 2 && style['active']}`}
              onClick={() => {
                setTag(2)
              }}
            >
              学校
            </div>
          </div>
        </div>
        {/* 是否设置为默认 */}
        <div className={style['tag-item']} style={{ justifyContent: 'space-between' }}>
          <div className={style['title']}>是否设为默认</div>
          <div className={style['btn']}>
            <Switch
              style={{ '--height': '24px' }}
              checked={checked}
              onChange={(checked) => {
                setChecked(checked)
              }}
            />
          </div>
        </div>
      </div>

      <div className={style['submit']}>
        <div
          className={style['cancel']}
          onClick={() => {
            navigate(-1)
          }}
        >
          取消
        </div>
        <div className={style['determine']} onClick={submit}>
          完成
        </div>
      </div>

      <Cascader
        options={options}
        visible={visible}
        onClose={() => {
          setVisible(false)
        }}
        value={[province, city, county]}
        onConfirm={(v) => {
          setProvince(v[0])
          setCity(v[1])
          setCounty(v[2])
        }}
      />
    </div>
  )
}
